/**
 * Created by zhaojm on 15/4/1.
 */

var PTM_RATIO = 32;
game.GameScene = cc.Scene.extend({

    _gameLayer : null,
    _uiLayer:null,
    _welcomeLayer:null,

    _world:null,

    _score : null,

    _gameStatus : null,
    initWorld : function(){

        var winSize = cc.winSize;
        var self = this;

        var b2Vec2 = Box2D.Common.Math.b2Vec2
            , b2BodyDef = Box2D.Dynamics.b2BodyDef
            , b2Body = Box2D.Dynamics.b2Body
            , b2FixtureDef = Box2D.Dynamics.b2FixtureDef
            , b2World = Box2D.Dynamics.b2World
            , b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
            , b2CircleShape = Box2D.Collision.Shapes.b2CircleShape
            , b2DebugDraw = Box2D.Dynamics.b2DebugDraw
            , b2ContactListener = Box2D.Dynamics.b2ContactListener;




        // Construct a world object, which will hold and simulate the rigid bodies.
        var gravity = new b2Vec2(0, -100);// 重力
        var allowSleep = true;
        this._world = new b2World(gravity, allowSleep);
        this._world.SetContinuousPhysics(true);



        //// ------------调试绘制
        //var canvas = document.getElementById('gameCanvas');
        //cc.log('convas..', canvas);
        //var context = canvas.getContext("2d");
        //cc.log('context==', context);
        ////
        ////var s = new cc.Sprite();
        ////this.addChild(s);
        ////
        //var debugDraw = new b2DebugDraw();
        ////设置绘图上下文
        //debugDraw.SetSprite(context);
        ////设置绘图比例
        //debugDraw.SetDrawScale(0.8);
        ////设置填充透明度
        //debugDraw.SetFillAlpha(0.3);
        ////设置线条厚度
        //debugDraw.SetLineThickness(1.0);
        //// 绘制所有的形状和关节
        //debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit | b2DebugDraw.e_aabbBit);
        ////使用调试绘图
        //this._world.SetDebugDraw(debugDraw);
        //-----------------------------




        var contactListener = new b2ContactListener();
        contactListener.BeginContact = function(contact){
            //cc.log('contact....');
            var roleA = contact.GetFixtureA().GetBody().GetUserData();
            var roleB = contact.GetFixtureB().GetBody().GetUserData();
            if(!roleA || !roleB){
                return;
            }
            if(roleA._className == 'Box2dBall'){
                if(roleB._className == 'Nail'){
                    self._gameStatus = 'gameover';
                }else if(roleB._className == 'Platform'){
                    roleA.jump();
                }
            }else if(roleB._className == 'Box2dBall'){
                if(roleA._className == 'Nail'){
                    self._gameStatus = 'gameover';
                }else if(roleA._className == 'Platform'){
                    roleB.jump();
                }
            }
        };

        this._world.SetContactListener(contactListener);


    },


    onEnter : function(){
        this._super();


        //if(game._Config.language == game._Enum.language.en) {
        //    window['Ads']['bottomAds']();
        //}



        this._gameStatus = 'welcome';
        this._score = 0;
        this.initWorld();

        game._Camera = game.Camera();

        this._uiLayer = new game.UILayer();
        this.addChild(this._uiLayer, 2);
        this._uiLayer.setScore(this._score);

        //this._gameLayer = new game.GameLayer(this._world);
        //this.addChild(this._gameLayer);

        this._scrollLayer = new game.ScrollLayer(this._world);
        this.addChild(this._scrollLayer);
        //
        this._heroLayer = new game.HeroLayer(this._world);
        this.addChild(this._heroLayer);

        this._welcomeLayer = new game.WelcomeLayer();
        this.addChild(this._welcomeLayer, 2);



        this.scheduleUpdate();

    },

    update:function(dt){
        this._super(dt);

        //game._Camera.update(dt);

        //this._gameLayer.update(dt);
        if(this._gameStatus == 'start'){
            //this._scrollLayer.update(dt);
        }else if(this._gameStatus == 'welcome'){

        }else if(this._gameStatus == 'gameover'){
            this.gameOver();
        }else if(this._gameStatus == 'hasgameover'){

        }



        var velocityIterations = 8;//8;
        var positionIterations = 1;
        var frameIterations = dt;

        this._world.Step(
            frameIterations // 帧率
            ,velocityIterations//速率
            , positionIterations//position iterations
        );
        //this._world.DrawDebugData();//绘制调试数据
        //this._world.ClearForces();//绘制完毕后清除外力


        //Iterate over the bodies in the physics world
        var outOfViewRoles = [];
        for (var b = this._world.GetBodyList(); b; b = b.GetNext()) {
            if (b.GetUserData() != null) {
                var role = b.GetUserData(); // role
                role.setPosition(cc.p(b.GetPosition().x * PTM_RATIO, b.GetPosition().y * PTM_RATIO));
                role.setRotation(-1 * cc.radiansToDegrees(b.GetAngle()));

                if(role._className == 'Nail' && role.getPositionX() < game._Camera.x){
                    outOfViewRoles.push(role);
                }
                //
                //// 碰撞检测
                //if(!this._isGameOver && this._gameLayer._hero && this._gameLayer._hero._className == 'Ball' ) {
                //    if (cc.rectIntersectsRect(role.getCollideRect(), this._gameLayer._hero.getCollideRect())) {
                //        if (role._className == 'Nail') {
                //            this._isGameOver = true;
                //            break;
                //        } else if (role._className == 'Platform') {
                //            this._gameLayer._hero.jump();
                //        }
                //
                //    }
                //}
            }
        }


        for(var i = 0; i < outOfViewRoles.length; i++){
            var role = outOfViewRoles[i];
            role.removeFromLayer();
            this.addScore();
        }
        outOfViewRoles = null;



    },

    onExit:function(){
        this.unscheduleUpdate();
        this._super();

    },

    start:function(){
        this._gameStatus = 'start';
        this._scrollLayer.start();
    },

    gameOver:function(){
        //this.unscheduleUpdate();
        cc.log('gameover...');
        this._gameStatus = 'hasgameover';
        this._scrollLayer.gameOver();

        var pos = this._heroLayer.getHeroPos();

        this._heroLayer.gameOver();

        //this._gameLayer.gameOver();


        this.addChild(new game.GameOverLayer({score:this._score}, this._world, pos));

    },

    addScore:function(){
        this._score++;
        this._uiLayer.setScore(this._score);
    },






});